package org.scboy.coobi;

import java.lang.reflect.InvocationTargetException;
import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.SQLException;

import org.scboy.coobi.caches.CoobiContext;
import org.scboy.coobi.caches.DbStyleCache;
import org.scboy.coobi.properties.CoobiProperties;
import org.scboy.coobi.scan.DbStyleScan;
import org.scboy.coobi.scan.FileScan;
import org.scboy.coobi.template.BeetlTemplate;
import org.scboy.coobi.template.DBTemplate;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;

import cn.hutool.log.Log;
import cn.hutool.log.LogFactory;


@Repository
public class InitCoobi {

	private static Log log=LogFactory.get();
	
	/**
	 * 框架初始化方法
	 * @return 
	 */
	public static void init(JdbcTemplate template,CoobiProperties properties) {
		
		//扫描支持的数据库样式
		DbStyleScan.doScan();
		
		//设置解析模板
		try {
			
			//外部自定义模板引擎
			CoobiContext.template=(DBTemplate)Class.forName(properties.getTmpClass()).getDeclaredConstructor().newInstance();
			//框架内部使用模板引擎
			CoobiContext.coobiTemplate=new BeetlTemplate();
		} catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException
				| NoSuchMethodException | SecurityException | ClassNotFoundException | InstantiationException e) {
			throw new RuntimeException(e);
		}
		
		//打印数据库相关信息，并设置数据库样式。
		try {
			Connection connection = template.getDataSource().getConnection();
			DatabaseMetaData metadata = connection.getMetaData();
			log.info("**********************************数据库信息************************************");
			log.info("*");
			String dbName=connection.getCatalog();
			log.info("*  数据库：" + dbName + "");
			log.info("*  数据库用户：" + metadata.getUserName() + "");
			String url = metadata.getURL();
			log.info("*  数据库连接：" + url + "");
			log.info("*  数据库产品名称：" + metadata.getDatabaseProductName() + "");
			log.info("*  数据库的版本：" + metadata.getDatabaseProductVersion() + "");
			log.info("*  驱动程序的名称：" + metadata.getDriverName() + "");
			log.info("*  驱动程序的版本：" + metadata.getDriverVersion() + "");
			log.info("*  是否允许只读：" + metadata.isReadOnly() + "");
			//log.info("*  数据库的系统函数的逗号分隔列表: "+ metadata.getSystemFunctions()+"");
			//log.info("*  数据库的时间和日期函数的逗号分隔列表: "+ metadata.getTimeDateFunctions()+"");
			//log.info("*  数据库的字符串函数的逗号分隔列表: "+ metadata.getStringFunctions()+"");
			//log.info("*  schema术语：" + metadata.getSchemaTerm() + "");
			log.info("*");
			log.info("********************************************************************************");
			connection.close();
			for (String jdbc : DbStyleCache.getDbs()) {
				if (url.indexOf(jdbc) > -1) {
					CoobiContext.dbStyle = DbStyleCache.getDbStyle(jdbc);
					CoobiContext.dbStyle.setDbName(dbName);
					break;
				}
			}
			if (CoobiContext.dbStyle==null){
				throw new RuntimeException("不支持该jdbc连接。");
			}
		} catch (SQLException e) {
			throw new RuntimeException("数据库异常。", e);
		}
		
		FileScan.scan();
	}
	
}
